<?php

namespace App\Models;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class JTK
{
    private $config = null;

    public function __construct()
    {
        $this->config = config('jtk');
    }

    public function actList($page = 1)
    {
        $url = $this->config['domain'] . '/union/act_list';

        $result = Http::get($url, [
            'apikey' => $this->config['apikey'],
            'page' => $page,
            'pageSize' => 100,
            'xcx_spread' => 0,
            'alipay_xcx_spread' => 0,
        ])->json();
        return $result['data'] ?? [];
    }

    public function orders($start_time, $end_time, $page = 1)
    {
        $url = $this->config['domain'] . '/union/orders';

        $result = Http::get($url, [
            'apikey' => $this->config['apikey'],
            'start_time' => $start_time, // 开始时间与结束时间不能超过1小时
            'end_time' => $end_time,
//            'query_type' => 0, // 1： 按支付时间 2：按更新时间 3：创建时间 ，默认：3
//            'sid' => 0, // 自定义参数跟单
//            'brand_id' => 1,// 品牌id 1 美团 2 饿了么 3 拼多多 4 京东 5 肯德基 6 电影 7 麦当劳 8 话费充值 9 百果园 10 奈雪的茶 11 瑞幸咖啡 12 星巴克 13 喜茶 14 唯品会 15 滴滴/花小猪 16 汉堡王 17 高德打车 18 电费充值 19 会员充值 20 特价快递 21 联联周边游 22 抖音联盟 23 必胜客 24 旅划算 25 大牌餐券 26 千千惠生活 27 流量卡 28 同程出行 29 华莱士 30 T3出行 31 景点门票 32 淘宝
//            'status' => 1, // 订单统一状态，0：未付款 1：已付款 2：待结算 3：已结算 4：无效订单
//            'order_sn' => '', // 订单号
//            'relation_flag_name' => '', // 第三方渠道标识
            'page' => $page,
            'pageSize' => 100,
        ])->json();

        return $result['data'] ?? [];
    }

    public function act($sid, $act_id)
    {
        $url = $this->config['domain'] . '/union/act';

        $result = Http::get($url, [
            'apikey' => $this->config['apikey'],
            'sid' => $sid,
            'act_id' => $act_id,
        ])->json();

        return $result['data'] ?? [];
    }

    public function generate($source_id, $activity_id)
    {
        $data = Cache::get($source_id . ":" . $activity_id);
        if ($data) {
            return $data;
        }
        $link = $this->act($source_id, $activity_id);
        if (!$link) {
            return [];
        }

        $data = [
            'link_h5' => $link['h5'],
            'app_id' => isset($link['we_app_info']) ? $link['we_app_info']['app_id'] ?? '' : '',
            'app_source' => $link['original_id'] ?? '',
            'link_mini' => isset($link['we_app_info']) ? $link['we_app_info']['page_path'] ?? '' : '',
            'code_link' => isset($link['we_app_info']) ? $link['we_app_info']['miniCode'] ?? '' : '',
            'poster_link' => isset($link['we_app_info']) ? $link['we_app_info']['miniCode'] ?? '' : '',
        ];

        Cache::put($source_id . ":" . $activity_id, $data, 60 * 60 * 24);
        return $data;
    }

    public static function callback($data)
    {
        PlatformCallback::query()->create([
            'platform' => $data['platform'],
            'body' => json_encode($data),
            'source_id' => $data['order_sn'],
        ]);
        $sid = $data['data']['sid'] ?? '';
        if (!$sid) return 'error';
        list($task_id, $uid) = explode('-', $sid);
        if (!$task_id || !$uid) return 'error';

        $task = Task::query()->find($task_id);
        if (!$task) return 'error';

        if ($data['data']['status'] == 3) {
            $log = UserTask::query()->create([
                'user_id' => $uid,
                'task_id' => $task_id,
                'status' => UserTask::STATUS_Y,
            ]);
            $count = UserTask::query()
                ->where(['user_id' => $uid, 'task_id' => $task_id])
                ->whereBetween('created_at', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
                ->count();
            if ($count == $task->number) {
                $jtk_share_fee = max($data['data']['jtk_share_fee'] ?: 0, 0);
                $user = User::query()->find($uid);
                $user->amount += round($jtk_share_fee * 100);
                $user->save();

                UserAmountLog::query()->create(
                    [
                        'user_id' => $uid,
                        'amount' => round($jtk_share_fee * 100),
                        'balance' => $user->amount,
                        'type' => 0,
                        'map_id' => $log->id,
                        'remark' => '赏金聚推客任务',
                    ]
                );
            }
        }

        return 'success';
    }
}
